package com.alibaba.nacos.core.distributed.distro.task.delay;

import com.alibaba.nacos.common.task.AbstractDelayTask;
import com.alibaba.nacos.common.task.NacosTask;
import com.alibaba.nacos.common.task.NacosTaskProcessor;
import com.alibaba.nacos.common.task.engine.NacosDelayTaskExecuteEngine;
import com.alibaba.nacos.core.distributed.distro.entity.DistroKey;
import com.alibaba.nacos.core.distributed.distro.task.execute.AbstractDistroExecuteTask;
import com.alibaba.nacos.core.distributed.distro.task.execute.DistroExecuteTaskExecuteEngine;
import com.alibaba.nacos.core.distributed.distro.task.execute.DistroSyncChangeTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class DistroDelayTaskExecuteEngine
        extends NacosDelayTaskExecuteEngine {

    @Autowired
    private DistroExecuteTaskExecuteEngine distroExecuteTaskExecuteEngine;


    @PostConstruct
    void init() {
        setDefaultTaskProcessor(new DistroDelayTaskProcessor());
    }

    @Override
    public void addTask(Object key,
                        AbstractDelayTask task) {
        super.addTask(key, task);
    }

    private class DistroDelayTaskProcessor
            implements NacosTaskProcessor {

        @Override
        public boolean process(NacosTask task) {
            if (task instanceof DistroDelayTask distroDelayTask) {
                DistroKey distroKey = distroDelayTask.getDistroKey();
                switch (distroDelayTask.getDataOperation()) {
                    case CHANGE, ADD -> {
                        DistroSyncChangeTask syncChangeTask = newDistroSyncChangeTask();
                        syncChangeTask.setDistroKey(distroKey);
                        distroExecuteTaskExecuteEngine.addTask(distroKey, syncChangeTask);
                        return true;
                    }
                    default -> {
                        return false;
                    }
                }
            }

            return true;
        }
    }

    @Lookup
    public DistroSyncChangeTask newDistroSyncChangeTask() {
        return null;
    }
}
